package com.wenx.v3system.modular.cloud.controller;

import com.wenx.base.rest.BaseRestController;
import com.wenx.v3core.response.R;
import com.wenx.v3secure.annotation.RequiresPermissions;
import com.wenx.v3system.modular.cloud.domain.dto.PermissionMoveDto;
import com.wenx.v3system.modular.cloud.domain.dto.SysPermissionDto;
import com.wenx.v3system.modular.cloud.domain.query.SysPermissionQuery;
import com.wenx.v3system.modular.cloud.service.SysPermissionRestService;
import com.wenx.v3system.modular.cloud.service.SysPermissionConditionRestService;
import com.wenx.v3secure.enums.SystemPermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import static com.wenx.v3secure.annotation.RequiresPermissions.Logical.OR;

/**
 * 权限管理Controller
 * 继承BaseRestController提供标准化CRUD操作
 * 同时保留权限特有的功能
 * 
 * @author wenx
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/v3/sys/permissions")
@Tag(name = "权限管理", description = "系统权限管理相关接口")
public class SysPermissionController extends BaseRestController<SysPermissionDto, SysPermissionQuery, SysPermissionRestService> {

    private final SysPermissionConditionRestService permissionConditionService;

    public SysPermissionController(SysPermissionRestService service, SysPermissionConditionRestService permissionConditionService) {
        super(service);
        this.permissionConditionService = permissionConditionService;
    }

    // ============= 基础CRUD操作 (继承自BaseRestController) =============

    @Override
    @PostMapping("/page")
    @Operation(summary = "分页查询权限", description = "根据查询条件分页获取权限列表")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R page(@RequestBody SysPermissionQuery query) {
        return R.ok(service.page(query));
    }

    @Override
    @GetMapping("/get/{id}")
    @Operation(summary = "获取权限详情", description = "根据ID获取权限详细信息")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R get(@PathVariable Serializable id) {
        return R.ok(service.get(id));
    }

    @Override
    @PostMapping("/add")
    @Operation(summary = "创建权限", description = "创建新的权限")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_CONFIG_CODE}, logical = OR)
    public R add(@RequestBody @Valid SysPermissionDto dto) {
        service.add(dto);
        return R.ok();
    }

    @Override
    @PutMapping("/update")
    @Operation(summary = "更新权限", description = "更新权限信息")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_CONFIG_CODE}, logical = OR)
    public R update(@RequestBody @Valid SysPermissionDto dto) {
        service.update(dto);
        return R.ok();
    }

    @Override
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除权限", description = "删除指定权限")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_CONFIG_CODE}, logical = OR)
    public R delete(@PathVariable Serializable id) {
        service.delete(id);
        return R.ok();
    }

    // ============= 扩展功能接口 =============

    /**
     * 获取所有权限（不分页）
     */
    @GetMapping("/all")
    @Operation(summary = "获取所有权限", description = "获取所有权限列表，不分页")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R getAllPermissions() {
        return R.ok(service.getMenuAll());
    }

    /**
     * 获取权限树
     */
    @GetMapping("/tree")
    @Operation(summary = "获取权限树", description = "获取权限树形结构")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R getPermissionTree(
            @Parameter(description = "权限类型") @RequestParam(required = false) String type,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        return R.ok(service.getPermissionTree(type, status));
    }

    /**
     * 获取菜单权限树
     */
    @GetMapping("/menu-tree")
    @Operation(summary = "获取菜单权限树", description = "获取菜单权限树形结构，用于路由生成")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R getMenuTree() {
        return R.ok(service.getMenuTree());
    }

    /**
     * 移动权限
     */
    @PutMapping("/move")
    @Operation(summary = "移动权限", description = "移动权限到新的父级或调整排序")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_CONFIG_CODE}, logical = OR)
    public R movePermission(@RequestBody @Valid PermissionMoveDto moveDto) {
        service.movePermission(moveDto.getPermissionId(), moveDto.getTargetParentId(), moveDto.getTargetSort());
        return R.ok("权限移动成功");
    }

    /**
     * 批量更新排序
     */
    @PutMapping("/batch-sort")
    @Operation(summary = "批量更新排序", description = "批量更新权限排序")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_CONFIG_CODE}, logical = OR)
    public R batchUpdateSort(@RequestBody List<Map<String, Object>> sortData) {
        service.batchUpdateSort(sortData);
        return R.ok();
    }

    /**
     * 检查权限编码是否存在
     */
    @GetMapping("/check-code")
    @Operation(summary = "检查权限编码", description = "检查权限编码是否已存在")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R checkPermissionCode(
            @Parameter(description = "权限编码") @RequestParam String code, 
            @Parameter(description = "排除的ID") @RequestParam(required = false) String excludeId) {
        boolean exists = service.existsByCode(code, excludeId);
        return R.ok(Map.of("exists", exists));
    }

    /**
     * 获取权限的子权限列表
     */
    @GetMapping("/{parentId}/children")
    @Operation(summary = "获取子权限", description = "获取指定权限的子权限列表")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R getChildPermissions(@PathVariable String parentId) {
        return R.ok(service.getChildPermissions(parentId));
    }

    // ============= 权限条件管理接口 =============

    /**
     * 获取权限条件列表
     */
    @GetMapping("/{permissionId}/conditions")
    @Operation(summary = "获取权限条件列表", description = "根据权限ID获取权限条件列表")
    @RequiresPermissions(value = {SystemPermission.SYSTEM_ALL_CODE, SystemPermission.SYSTEM_READ_CODE}, logical = OR)
    public R getPermissionConditions(@PathVariable Long permissionId) {
        return R.ok(permissionConditionService.getByPermissionId(permissionId));
    }
}